<template>
    <div>
        <h1>{{title}}</h1>
        <input
            v-model="goodName"
            type="text"
            placeholder="水果名称"
        /><br />
        <input 
            v-model="goodPrice"  
            type="number" 
            placeholder="价格" 
        /><br />
        <button @click="addGood" >添加商品</button>
        <ul>
            <li
                v-for="(good, index) in goods"
                :key="good.id" 
            >
                {{good.title}}:
                ¥{{good.price}}
                <button @click="addCart(index)">添加购物车</button>
            </li>
        </ul>
    </div>
</template>

<script>

let getGoods = () => {
    return new Promise((resolve) => {
        let xhr = new XMLHttpRequest()
        xhr.open('GET', '/api/goods')
        xhr.send()
        xhr.onload = function() {
            resolve(JSON.parse(xhr.response))
        }
    })
}

export default {
    name: 'shop',
    props: {
        title: {
            type: String,
            default: 'Hello ',
            required: true,
        }
    },
    data() {
        return {
            goodName: '',
            goodPrice: 0,
            goods: [],
            cartList: []
        }
    },

    beforeCreate () {
        console.log('1 beforeCreate')
    },

    async created() {
        console.log('2 created')
        let res = await getGoods()
        this.goods = res.data
    },

    beforeMount () {
        console.log('3 beforeMount')
    },

    mounted() {
        console.log('4 mounted')
    },

    beforeUpdate() {
        console.log('5 beforeUpdate')
    },
    
    updated() {
        console.log('6 updated')
    },

    methods: {
        addCart: function(i) {
            const good = this.goods[i]
            // 购物车里是否已经选择了
            this.$root.$emit('addCart', good)
        },
        addGood: function() {
            if (this.goodName) {
                this.goods.push({
                    id: this.goods.length, 
                    title: this.goodName, 
                    price: this.goodPrice
                })
                this.goodName = ''
                this.goodPrice = 0
            }
        }
    }
}
</script>

<style lang="scss" scoped>

</style>